<!--
*@Author: zt
*@Description: 动态表单创建
*@Date: 2024-09-10 
-->
<template>
  <a-layout class="f-h-100 s-bg-white" id="test">
    <u-table-header>
      <a-row>
        <a-col :span="12">
          <a-space v-if="route.params.pType == '2'">
            <u-form
              :model="searchF.model"
              :elements="searchEl"
              class="f-w-auto"
            ></u-form>
          </a-space>
          <a-space v-if="route.params.pType == '2'" style="margin-left: 10px">
            <u-icon-button @click="getSearch">查询</u-icon-button>
          </a-space>
        </a-col>
        <a-col :span="12">
          <a-row justify="end" style="padding-bottom: 10px">
            <a-space>
              <u-icon-button
                itype="add"
                @click="showEdit = true"
                v-if="route.params.pType == '1'"
              >
                新增
              </u-icon-button>
              <u-icon-button
                itype=""
                @click="showEditClick"
                v-if="route.params.pType == '1'"
              >
                修改
              </u-icon-button>

              <u-icon-button
                itype=""
                @click="showFlow = true"
                v-if="showTabelFlow"
              >
                流程记录
              </u-icon-button>
              <u-icon-button
                itype="report"
                @click="auditAboutClick('1')"
                v-if="showTabelFlow && route.params.pType == '1'"
              >
                上报
              </u-icon-button>
              <u-icon-button
                itype="audit"
                @click="auditAboutClick('2')"
                v-if="route.params.pType == '2' && showAuditBnt"
              >
                审核
              </u-icon-button>
              <u-icon-button
                itype="recall"
                @click="auditAboutClick('4')"
                v-if="showTabelFlow"
              >
                取回
              </u-icon-button>
              <u-icon-button
                itype="close"
                @click="auditAboutClick('3')"
                v-if="route.params.pType == '2' && showAuditBnt"
              >
                退回
              </u-icon-button>
              <u-icon-button itype="delete" @click="deleteBtn">
                删除
              </u-icon-button>
            </a-space>
          </a-row>
        </a-col>
      </a-row>
    </u-table-header>
    <u-table-content>
      <u-table
        :columns="columns"
        :data="tabData"
        :loading="loading"
        v-model:pagination="pagenation"
        :scroll="{ y: useTableScroll() }"
        @onDblclick="onDblclick"
        @onSelect="({ selectedRows }) => (tabSelData = selectedRows)"
      ></u-table>
    </u-table-content>
  </a-layout>

  <!-- 编辑弹窗 -->
  <Edit
    v-model:open="showEdit"
    wrap-class-name="full-modal"
    :keyid="keyid"
    :isAudited="showAuditBnt"
    @success="getSearch(1), (showEdit = false), (keyid = '')"
    @close="getSearch(1), (showEdit = false), (keyid = '')"
  />

  <!-- 流程记录 -->
  <u-act-flowd
    v-model:open="showFlow"
    :selDatas="tabSelData"
    busiType="form_apply"
  />
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { _IFormEl } from '@/components/common/form/interface';
import { useTableScroll } from '@/hooks/useTable';
import { messageC, alertC } from '@/util/common';
import { storeToRefs } from 'pinia';
import { useBaseStore, useLoginStore } from '@/store';
import { IAuditParams, useAuditAbout } from '@/hooks/useAudit';
import { usePageTypeShow, useSearchShow } from '@/hooks/useAuditEl';
import Edit from './edit.vue';
import * as dynamicFormsApi from '@/service/emergency/dynamicForms/index';
import * as dynamicFormsItemApi from '@/service/emergency/dynamicFormsItem/index';

const route = useRoute();
const router = useRouter();
const { ISPROXY } = storeToRefs(useBaseStore());
const { userInfo } = storeToRefs(useLoginStore());
const loading = ref(false);
const userInfoName = userInfo.value.name;
let showTabelFlow = ref(false);
const routeArr = route.path.split('/');

let keyid = ref('');
const showFlow = ref(false);
let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: total => `共 ${total} 条`,
});
let searchF = reactive<any>({
  model: {
    adstatus: 0,
  },
});

// 曾经办，不显示审核和退回按钮
const showAuditBnt = ref<boolean>(
  useSearchShow(searchF.model, '1', {
    key: 'adstatus',
    result: false,
    noResult: true,
  })
);

const tabSelData = ref<any[]>([]);
let showEditRow = ref(false);
const searchEl: Array<_IFormEl> = [
  {
    label: '数据状态',
    key: 'adstatus',
    element: 'select',
    col: { span: 24 },
    formItemProps: {
      labelWidth: '100px',
    },
    componentProps: {
      allowClear: false,
      options: [
        {
          label: '曾经办',
          value: 1,
        },
        {
          label: '待操作',
          value: 0,
        },
      ],
    },
  },
];

// 列表
let tabData = ref([]);
let columns = ref<any>([
  {
    dataIndex: 'index',
    title: '序号',
    width: 60,
    align: 'center',
    customRender: ({ text, record, index }) => {
      return index + 1;
    },
  },
]);

// 上报、审核、退回
const auditAbout = async (type: string) => {
  const auditParams: IAuditParams = {
    type: 'form_apply',
    fkdycform: route.params.bzType,
    selDatas: tabSelData.value,
  };
  try {
    const res = await useAuditAbout(type, auditParams);
    pagenation.current = 1;
    await getSearch();
  } catch (error) {}
};

// 事件额外操作
const auditAboutClick = async (type: string) => {
  if (tabSelData.value.length != 1) {
    alertC('请选择一条数据!', 'warning');
    return;
  }
  if (type == '3' || type == '2') {
    if (
      !(tabSelData.value[0]['reauditusername'] || '').includes(userInfoName)
    ) {
      alertC('您无权限操作该数据！');
      return;
    }
  }

  await auditAbout(type);
};

// 查询数据
const getSearch = async (index?) => {
  loading.value = true;
  let tform = JSON.parse(JSON.stringify(searchF));
  tform.model.keywords = searchF.keywords;
  tform.model.isAudit = route.params.pType == '2' ? 1 : 0;
  tform.model.fkdycform = route.params.bzType;
  if (index == 1) {
    pagenation.current = 1;
  }
  tform.current = pagenation.current;
  tform.size = pagenation.pageSize;
  // 表头赋值
  columns.value = [
    {
      dataIndex: 'index',
      title: '序号',
      width: 60,
      align: 'center',
      customRender: ({ text, record, index }) => {
        return index + 1;
      },
    },
  ];

  let formList = {};
  const res = await dynamicFormsItemApi.page({ ...tform });
  // 表单数据
  const result = await dynamicFormsApi.query(route.params.bzType);
  if (result.code == 0) {
    columns.value = [
      {
        dataIndex: 'index',
        title: '序号',
        width: 60,
        align: 'center',
        customRender: ({ text, record, index }) => {
          return index + 1;
        },
      },
    ];

    formList = JSON.parse(result.data.formjson);

    formList.list.map(e => {
      columns.value.push({
        dataIndex: e.id,
        title: e.name,
        align: 'center',
        customRender: ({ text, record, index }) => {
          if (e.itemType == 'switch') {
            if (text == 'true') {
              return e.checkedChildren;
            } else if (text == 'false') {
              return e.unCheckedChildren;
            } else {
              return text;
            }
          } else if (e.itemType == 'select') {
            return e.options.map(index => {
              if (text == index.id) {
                return index.label;
              }
            });
          } else {
            return text;
          }
        },
      });
    });

    if (result.data.ishaveaudit == 1) {
      columns.value.push(
        { dataIndex: 'taskname', title: '流程环节', width: 150 },
        {
          dataIndex: 'reauditusername',
          title: '当前审核人',
          width: 150,
          align: 'center',
        }
      );
      showTabelFlow.value = true;
    }
    columns.value = Array.from(new Set(columns.value));
  }

  if (res.code == 0) {
    tabData.value = res.data.records;
  }
  setTimeout(() => {
    loading.value = false;
  }, 300);
};

// 删除
const deleteBtn = async () => {
  if (tabSelData.value.length == 0) {
    alertC('请先选择要删除的数据!', 'warning');
    return;
  }
  let ids = tabSelData.value.map(item => item.keyid);
  alertC('确认删除选中的数据?', 'confirm').then(async () => {
    try {
      const res = await dynamicFormsItemApi.del({ ids: ids.join(',') });
      if (res.code == 0) {
        getSearch(1);
        messageC(res.msg, 'success');
      } else {
        alertC(res.msg, 'warning');
      }
    } catch (error) {}
  });
};

//编辑打开事件
const showEditClick = () => {
  if (tabSelData.value.length !== 1) {
    alertC('能且只能选择一条数据', 'warning');
    return;
  }
  keyid.value = tabSelData.value[0]['keyid'];
  showEdit.value = true;
};

//填报列表数据展示
const onDblclick = record => {
  keyid.value = record['keyid'];
  showEdit.value = true;
};

//查看报表数据
const pushClick = () => {
  if (tabSelData.value.length !== 1) {
    alertC('能且只能选择一条数据', 'warning');
    return;
  }
  keyid.value = tabSelData.value[0]['keyid'];
  showEditRow.value = true;
};

onMounted(async () => {
  // await getDetails()
  await getSearch(1);
});

//获取详情数据
// const getDetails = async () => {
//   // const bzType = route.path.split('/')[route.path.split('/').length - 1]
//   // const res = await dynamicFormsItemApi.query(bzType)

// }

// 编辑
let dialogTitle = ref<string>('创建任务');
let dialogRowTitle = ref<string>('表数据');

let showEdit = ref<boolean>(false);

// 导入
let showImp = ref<boolean>(false);
</script>

<style lang="scss" scoped>
.icons-list :deep(.anticon) {
  margin-right: 6px;
  font-size: 24px;
}
</style>
